<?php
namespace soa\kbpush\ios;
/**
 * Class ios
 * @package soa\kbpush\ios;
 */
class ios
{
    /**
     * @var null
     */
    private $fp = null;

    /**
     * @param $info
     * @return int|string
     */
    public function send($string)
    {
        header("Content-type: text/html; charset=utf-8");

        //$deviceToken = $info['device']['apple_token'];
        //echo $deviceToken.'<hr>';
        //$custom_content = $info['message']['custom_content'];
       /* print_r($custom_content);
        echo '<hr>';*/
        // 处理弹出消息
      /*  $alert = $custom_content['title'].'：'.$custom_content['description'];
        //if($info['app'] == "weikuaidi") {
            switch($custom_content['message_type']) {
                // 流转信息
                case 'multinfo':
                    $alert = "宝贝新消息（" . $custom_content['express_no'] . ")： " . $custom_content['description'];
                    break;
                // 留言
                //case 'liuyan':
                    //$alert = $custom_content['title'].'：'.$custom_content['description'];
                    //break;
                // 投诉
                case 'complain':
                    $alert = "投诉新消息 " . "单号:" . $custom_content['deliver_no'] . "," . $custom_content['status'];
                    break;
                // 订单
                case 'order':
                    $alert = "订单新消息 " . "订单:" . $custom_content['order_id'] . "," . $custom_content['description'];
                    break;
            }*/
        //}
       //var_dump($alert);

        $alert = mb_strimwidth($string, 0, 75, "...", 'utf-8');

        //$body = $custom_content;
        // badge
        $badge = 1;

        $fp = $this->getAppleConnect();
        if(!empty($fp)) {

            //unset($body['title'], $body['description']);


        $body=array(
            'aps'=>array(
                'alert' =>$alert,
                'badge' => 1,
                'sound' => 'default',
            )
            );
           //echo '<hr>';
            //print_r($body);
            // Encode the payload as JSON
            $payload = json_encode($body);

            // Build the binary notification
            $msg = chr(0) . pack('n', 32) . pack('H*', '499a872f1ecbc8de022c7faf6e318ad679846d48cbc8417f3db66ce8068ca1a6') . pack('n', strlen($payload)) . $payload;
            echo '<hr>';
            //echo'msg::';
            //echo $msg;
            // Send it to the server
            $result = fwrite($fp, $msg, strlen($msg));
            var_dump($result);
            if(!$result) {
                echo 'Error, notification not sent' . PHP_EOL;
                // 重新建立连接，并重试
                // 先关闭连接
                $this->getAppleConnect($info['app'], false);
                // 再建立连接
                $fp = $this->getAppleConnect($info['app']);
                if(!empty($fp)) {
                    // 再次尝试发送数据
                    $result = fwrite($fp, $msg, strlen($msg));
                    if(!$result)
                        $result = 'send data error!';
                    else
                        $result = 'sent '.$result.' bytes of data after reconnect.';
                } else {
                    $result = 'failed to reconnect!';
                }
            } else {
                echo 'notification sent!' . PHP_EOL;
                echo $result = 'sent '.$result.' bytes of data.';
            }
        } else {
            $result = 'failed to setup connection1';
        }
        // Close the connection to the server
        //get_apple_connection($info, false);
        return $result;
    }


    /**
     * @param string $app
     * @param bool $close
     * @return bool|null|resource
     */
    public function getAppleConnect($app = '', $close = false)
    {
        /*if(!empty($this->fp[$app]) && $close === true) {
            return fclose($this->fp[$app]);
        }

        if(!empty($this->fp[$app])) {
            return $this->fp[$app];
        }*/

        // 获取配置文件
        /*$config = config::get('push', 'ios');

        $passphrase = $config[$app]['passphrase'];*/


        $pem = dirname(__FILE__) . '/IOSSDevelopment.pem'  ;
        $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', $pem);
        stream_context_set_option($ctx, 'ssl', 'passphrase', 'wandan');

        error_reporting(E_ALL);
       // set_error_handler(array($this, 'errorHandler'), E_ALL);

        $fp = stream_socket_client(
            //'ssl://gateway.push.apple.com:2195', //online
            'ssl://gateway.sandbox.push.apple.com:2195',  //offline
            $err,
            $errstr,
            6000,
            STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT,
            $ctx
        );

        if (!$fp) {
            echo 'Connected to APNS' . PHP_EOL;
            return null;
        }

        return $this->fp[$app] = $fp;
    }
}